package br.biofoco.p2p.rpc.tcp;

import java.io.IOException;
import java.net.Socket;
import java.util.Map;
import java.util.Random;

import br.biofoco.p2p.peer.PeerNode;
import br.biofoco.p2p.rpc.messaging.WireRequestMessage;
import br.biofoco.p2p.rpc.messaging.WireResponseMessage;
import br.biofoco.p2p.rpc.messaging.TransportClient;
import br.biofoco.p2p.utils.Serializer;
import br.biofoco.p2p.utils.SerializerFactory;

class TcpTransportClient implements TransportClient {
	
	private final Socket socket;
	private Serializer serializer = SerializerFactory.getSerializer();
	private Random random = new Random(System.nanoTime());

	TcpTransportClient(Socket socket) throws IOException {
		this.socket = socket;
	}
	
	private int createRandomMessageID() {
		return random.nextInt() & 0x0fffffff;
	}

	@Override
	public void close() throws IOException {
		WireRequestMessage wireMessage = new WireRequestMessage(createRandomMessageID(), "CLOSE", "Bye, bye");
		serializer.serialize(wireMessage, socket.getOutputStream());
		socket.close();
	}

	@Override
	public String invokeCommand(String command, String... params) throws IOException {
			
		WireRequestMessage outgoingMessage = new WireRequestMessage(createRandomMessageID(), command, params);
		serializer.serialize(outgoingMessage, socket.getOutputStream());

		WireResponseMessage incomingMessage = serializer.unserialize(socket.getInputStream(), WireResponseMessage.class);
		
		return (incomingMessage == null) ? "no result" : incomingMessage.getContent();
	}

}
